<template>
  <a-card :bordered="false">
    <h3>内容详情</h3>
    <div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
      <a-alert style="flex: 1;" v-if="details.literalReason || details.pictureReason" message="内容中红色标记的内容可能为敏感内容或图片，请重点核对" type="warning" show-icon />
      <template v-else>
        <a-alert style="flex: 1;" v-if="details.status == 0" message="内容已审核通过，将根据分发规则分发在社区" type="success" show-icon />
        <a-alert style="flex: 1;" v-if="details.status == 1" :message="message" type="error" show-icon />
      </template>
      <a-button v-if="details.status == 0" style="margin-left: 40px;" @click="handleDisable">禁用</a-button>
      <a-popconfirm v-if="details.status == 1" title="确定启用该条内容吗？"  ok-text="确定" cancel-text="暂不" @confirm="handleEnable">
        <a-button style="margin-left: 40px;">启用</a-button>
      </a-popconfirm>
    </div>
    <div class="user-infor">
      <a-descriptions :column="2">
        <a-descriptions-item label="内容ID">{{details.id}}</a-descriptions-item>
        <a-descriptions-item label="内容评级">{{details.contentLevel}}级 <a-icon type="form" @click="contentLevelVisible = true"/></a-descriptions-item>
        <a-descriptions-item label="发布人">{{ details.userNickname }}/{{ details.phone }}(社区ID：{{ details.communityId }})</a-descriptions-item>
        <a-descriptions-item label="发布人身份">{{ details.identityName }}</a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ details.createTime }}</a-descriptions-item>
        <a-descriptions-item label="更新时间">{{ details.updateTime }}</a-descriptions-item>
        <a-descriptions-item label="发布时间">{{ details.releaseTime }}</a-descriptions-item>
        <a-descriptions-item label="发布渠道">{{ details.releaseChannel }}</a-descriptions-item>
      </a-descriptions>
    </div>
    <a-divider />
    <a-row>
      <a-col :span="12">
        <a-descriptions :column="1">
          <a-descriptions-item label="内容标题" >
            <div v-html="details.contentTitle"></div>
          </a-descriptions-item>
          <a-descriptions-item label="内容正文">
            <span class="content" v-html="bodyContent"></span>
            <a-alert v-if="details.literalNote" style="margin-top: 5px;" :message="details.literalNote" type="error" />
          </a-descriptions-item>
          <a-descriptions-item label="关联商品">
            <span class="img-wrapper" v-if="details.communityTopicAssGoodsDtoList && details.communityTopicAssGoodsDtoList.length">
            <div class="img-list">
              <a-tooltip v-for="(item, index) in details.communityTopicAssGoodsDtoList.slice(0, 5)"  :key="index">
                <img class="img" v-if="item.image" :src="item.image" alt="" @click="productVisible=true,productList=details.communityTopicAssGoodsDtoList" >
                <img class="img" v-else src="https://picttype1.jnby.com/community/goods/pl-goods.png" @click="productVisible=true,productList=details.communityTopicAssGoodsDtoList" alt=""  />
                <template slot="title">
                  {{item.brandName}}-{{item.productNo}}
                </template>
              </a-tooltip>
            </div>
          <div class="img-text" @click="productVisible=true,productList=details.communityTopicAssGoodsDtoList">共{{details.communityTopicAssGoodsDtoList.length}}件</div>
        </span>
          </a-descriptions-item>
          <a-descriptions-item label="关联话题">
            <a-tag color="#2db7f5" v-if="details.topicName">#{{details.topicName}}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="发布IP属地">
           {{details.territorial}}
          </a-descriptions-item>
        </a-descriptions>
      </a-col>
      <a-col :span="12">
        <a-descriptions :column="1">
          <a-descriptions-item label="图片/视频">
            <div class="media-list" >
            <template v-if="details.contentType == 0">
              <div class="media-item img" v-for="(item, index) in pictureVideo"  @click="handleShowImg(index, pictureVideo.map(e => e.url))" :key="index">
                <img class="media-item img" :src="item.url" alt="" >
                <a-tooltip>
                  <a-icon type="exclamation-circle" class="icon" v-if="item.isViolations" />
                  <template slot="title">
                    {{ item.explain }}
                  </template>
                </a-tooltip>
              </div>
            </template>
            <div class="media-item video" v-if="details.contentType == 1">
              <a-tooltip>
                <a-icon type="exclamation-circle" class="icon" v-if="pictureVideo.length && pictureVideo[0].isViolations" />
                <template slot="title">
                  {{ pictureVideo[0].explain }}
                </template>
              </a-tooltip>
              <img  class="media-item video" @click="handlePreview(pictureVideo.map(e => e.url).join(','))"  :src="details.cover" alt=""></img>
            </div>
          </div>
          </a-descriptions-item>
          <!-- <a-descriptions-item label="浏览/播放">
            {{browseNumber || 0}}/{{playNumber || 0}}
          </a-descriptions-item> -->
          <a-descriptions-item label="浏览">
            {{browseNumber || 0}}/{{totalBrowseNumber || 0}}
          </a-descriptions-item>
          <a-descriptions-item label="播放">
            {{playNumber || 0}}
          </a-descriptions-item>
        </a-descriptions>
      </a-col>
    </a-row>
    <a-tabs :activeKey="activeKey"  @change="onChangeActiveKey">
      <a-tab-pane :tab="`评论(${commentsNumber || 0})`" :forceRender="false" key="1">
        <a-row type="flex" :gutter="10" v-if="details.status == 0">
          <a-col flex="100px">
            <a-select style="width: 100%;" v-model="officialNoId" placeholder="请选择" show-search :filter-option="filterOption">
              <a-select-option :value="0" disabled>官方账号</a-select-option>
              <a-select-option v-for="item in officialNoList" :value="item.id" :key="item.id">{{item.userNickname}}</a-select-option>
            </a-select>
          </a-col>
          <a-col flex="auto">
            <a-input v-model.trim="content" :maxLength="2000" placeholder="发表你的评论~" allowClear />
          </a-col>
          <a-col flex="60px">
            <a-button type="primary" @click="handleCommentAdd">评论</a-button>
          </a-col>
        </a-row>
        <a-divider v-if="details.status == 0" />
        <CommentList @onSuccess="updateList" :parentOfficialNoId.sync="officialNoId" :officialNoList="officialNoList" v-show="activeKey == 1" :commentList="list"></CommentList>
      </a-tab-pane>
      <a-tab-pane :tab="`赞(${praiseNumber || 0}/${totalPraiseNumber || 0})`" key="2">
        <CommentUserList v-show="activeKey == 2" :commentUserList="list"></CommentUserList>
      </a-tab-pane>
      <a-tab-pane :tab="`转发(${turnNumber || 0})`" key="4">
        <CommentUserList v-show="activeKey == 4" :commentUserList="list"></CommentUserList>
      </a-tab-pane>
      <a-tab-pane :tab="`不喜欢(${noLikeNumber || 0})`" key="5">
        <CommentUserList v-show="activeKey == 5" :commentUserList="list"></CommentUserList>
      </a-tab-pane>
    </a-tabs>
    <div style="text-align: center;" v-if="list.length"><a-pagination :pageSize="pageSize" :show-total="total => `共 ${total} 条`" :current="pageNo" @change="onChange" :total="total" /></div>
    <div class="ant-empty ant-empty-normal" v-else>
      <div class="ant-empty-image">
        <svg width="64" height="41" viewBox="0 0 64 41" xmlns="http://www.w3.org/2000/svg">
          <g transform="translate(0 1)" fill="none" fillRule="evenodd">
            <ellipse fill="#F5F5F5" cx="32" cy="33" rx="32" ry="7"></ellipse>
            <g fillRule="nonzero" stroke="#D9D9D9">
              <path d="M55 12.76L44.854 1.258C44.367.474 43.656 0 42.907 0H21.093c-.749 0-1.46.474-1.947 1.257L9 12.761V22h46v-9.24z"></path>
              <path
                d="M41.613 15.931c0-1.605.994-2.93 2.227-2.931H55v18.137C55 33.26 53.68 35 52.05 35h-40.1C10.32 35 9 33.259 9 31.137V13h11.16c1.233 0 2.227 1.323 2.227 2.928v.022c0 1.605 1.005 2.901 2.237 2.901h14.752c1.232 0 2.237-1.308 2.237-2.913v-.007z"
                fill="#FAFAFA"
              ></path>
            </g>
          </g>
        </svg>
      </div>
      <p class="ant-empty-description">暂无数据</p>
    </div>
    <a-modal title="调整内容评级" :visible="contentLevelVisible" width="500px" @ok="handleContentLevelSubmit" @cancel="contentLevelVisible = false">
      <a-form-model ref="contentLevelForm" :model="contentLevelForm" :rules="contentLevelRules">
        <a-form-model-item label="选择内容评级（单选）" prop="contentLevel">
          <a-radio-group v-model="contentLevelForm.contentLevel">
            <a-radio value="A">A类</a-radio>
            <a-radio value="B">B类</a-radio>
            <a-radio value="C">C类</a-radio>
            <a-radio value="D">D类</a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <ProductListModal :visible.sync="productVisible" :productList="productList"></ProductListModal>
    <ParagraphPic :current="imgCurrent" :visible.sync="imgVisible" :imgs="imgs"></ParagraphPic>
    <PreviewVideo :visible.sync="previewVisible" :videoUrl="videoUrl"></PreviewVideo>
    <DisableModal :visible.sync="disableVisible" :whyList="whyList" @onOk="onOk"></DisableModal>
  </a-card>
</template>
<script>
import ParagraphPic from '../../components/ParagraphPic'
import PreviewVideo from '../../components/PreviewVideo'
import CommentList from '../../components/CommentList'
import CommentUserList from '../../components/CommentUserList'
import ProductListModal from '../../components/ProductListModal'
import { contentDetails, contentAddOrUpdate, contentCommentsPage, contentConoper, commentAdd, contentConoperNUm } from '@/api/micromall/communityContent'
import { mapGetters } from 'vuex'
import { userList, whyPage } from '@/api/micromall/communityUser'
import DisableModal from '../../components/DisableModal'
import Cookie from "js-cookie"
export default {
  components: {
    ParagraphPic,
    PreviewVideo,
    CommentList,
    CommentUserList,
    ProductListModal,
    DisableModal
  },
  data() {
    return {
      totalBrowseNumber: 0,
      totalPraiseNumber: 0,
      browseNumber: 0,
      playNumber: 0,
      commentsNumber: 0,
      praiseNumber: 0,
      turnNumber: 0,
      noLikeNumber: 0,
      bodyContent: '',
      pictureVideo: [],
      activeKey: '1',
      pageNo: 1,
      pageSize: 10,
      total: 0,
      list: [],
      whyList: [],
      content: '',
      officialNoId: Number(Cookie.get('officialNoId')) || 0,
      officialNoList: [],
      disableVisible: false,
      details: {},
      videoUrl: '',
      previewVisible: false,
      imgCurrent: 0,
      imgVisible: false,
      imgs: [],
      productVisible: false,
      productList: [
      ],
      contentLevelForm: {
        contentLevel: ''
      },
      contentLevelVisible: false,
      contentLevelRules: {
        contentLevel: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getWhyPage()
    this.getDetails()
    this.getOfficialNoList()
    this.getCount()
  },
  computed: {
    message() {
      const details = this.details
      if (details.disableNote) {
        return '内容已禁用（原因：' + details.whyName + '（' + details.disableNote + '），禁用时间：' +details.updateTime +'）'
      } else {
        return '内容已禁用（原因：' + details.whyName + '，禁用时间：' +details.updateTime +'）'
      }
      
    }
  },
  watch: {},
  methods: {
    // 获取详情
    getDetails() {
      const id = this.$route.params.id
      const data = {
        id
      }
      contentDetails(data)
        .then(res => {
          if (res.code === 200) {
          const {bodyContent, contentLevel, contentTitle, literalReason, pictureVideo, totalPraiseNumber, totalBrowseNumber, pictureReason} = res.data
          this.bodyContent = bodyContent
          this.totalBrowseNumber = totalBrowseNumber
          let currentContentTitle = contentTitle
          const currentPictureReason = pictureReason ? JSON.parse(pictureReason) : []
          if (pictureVideo) {
            this.pictureVideo = pictureVideo.split(',').map(e => {
              const index = currentPictureReason.map(i => i.url).indexOf(e)
              return {
                url: e,
                explain: index >=0 ? currentPictureReason[index].explain : '',
                isViolations: currentPictureReason.map(i => i.url).includes(e)
              }
            })
          }
          if (literalReason) {
            literalReason.split(',').forEach(e => {
              if (e) {
                currentContentTitle = currentContentTitle.replace(new RegExp(e,'g'), `<span style="color: red;">${e}</span>`)
                this.bodyContent = this.bodyContent.replace(new RegExp(e,'g'), `<span style="color: red;">${e}</span>`)
              }
            })
          }
          this.details = {...res.data, contentTitle: currentContentTitle}
          this.contentLevelForm.contentLevel = contentLevel
          this.getList(true) // 获取评论
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {})
    },

    // 获取评论，赞，转发，不喜欢数量
    getCount() {
      const data = {
        contentId: this.$route.params.id
      }
      contentConoperNUm(data).then(res => {
        if (res.code === 200) {
          const {commentsNumber, praiseNumber, turnNumber, noLikeNumber, browseNumber, playNumber, totalPraiseNumber } = res.data
          this.commentsNumber = commentsNumber
          this.praiseNumber = praiseNumber
          this.turnNumber = turnNumber
          this.noLikeNumber = noLikeNumber
          this.browseNumber = browseNumber
          this.playNumber = playNumber
          this.totalPraiseNumber = totalPraiseNumber
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 
    getList(isRemove){
      if (isRemove) {
        this.list = []
        this.pageNo = 1
        this.total = 0
      }
      const data = {
        contentId: this.details.id,
        current: this.pageNo,
        size: this.pageSize,
        type: this.activeKey// 2获赞 4转发 5不喜欢
      }
      const list = this.activeKey == 1 ? contentCommentsPage : contentConoper
      list(data)
        .then(res => {
          const {records, current, total} = res.data
          if (res.code === 200) {
          this.list = records
          this.total = total
          // this.pageNo = current
          } else {
            this.$message.error(res.msg)
          }
        })
    },

    onChangeActiveKey(e) {
      this.activeKey = e
      this.getList(true)
      this.getCount()
    },

    // 分页
    onChange(e) {
      this.pageNo = e
      this.getList(false)
    },

    // 禁用原因
    getWhyPage() {
      // 3内容禁用原因
      const data = {
        type: 3,
        status: 0
      }
      whyPage(data).then(res => {
        if (res.code === 200) {
          this.whyList = res.data.records
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 获取官方账号
    getOfficialNoList() {
      const data = {
        current: 1,
        size: 1000,
        identityId: 1,
        status: 0
      }
      userList(data).then(res => {
        if (res.code === 200) {
          this.officialNoList = res.data.records
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 禁用
    handleDisable() {
      this.disableVisible = true
    },

    // 禁用弹窗确认
    onOk(v) {
      const { note, why } = v
      const data = {
        id: this.details.id,
        status: '1',
        disableWhy: why.map(e => e.id).join(','),
        disableNote: note,
        whyName: why.map(e => e.whyName).join(',')
      }
      contentAddOrUpdate(data).then(res => {
        if (res.code === 200) {
         this.getDetails()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),

    // 启用
    handleEnable() {
      const data = {
        id: this.details.id,
        status: '0',
        enable: 1
      }
      contentAddOrUpdate(data).then(res => {
        if (res.code === 200) {
         this.getDetails()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 预览视频
    handlePreview(url) {
      this.videoUrl = url
      this.previewVisible = true
    },

    // 内容评级
    handleContentLevelSubmit() {
      this.$refs.contentLevelForm.validate(valid => {
        if (valid) {
          const data = {
            ...this.details,
            ...this.contentLevelForm
          }
          this.contentLevelVisible = false
          contentAddOrUpdate(data).then(res => {
            if (res.code === 200) {
            this.getDetails()
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

     // 回复消息
    handleCommentAdd() {
      const officialNoList = this.officialNoList.filter(e => this.officialNoId == e.id)
      if (!this.officialNoId ) {
        this.$message.info('请选择官方账号')
        return
      }
      if (!officialNoList.length) {
        this.$message.info('官方账号有变动,请重新选择官方账号')
        return
      }
      if (!this.content) {
        this.$message.info('请发表你的评论~')
        return
      }
      const officialNo = officialNoList[0]
      const { id, userNickname, headPortrait } = officialNo
      const data = {
        userId: id,
        userNickname,
        headPortrait,
        content: this.content,
        status: 0,
        contentId: this.details.id
      }
      commentAdd(data).then(res => {
        if (res.code === 200) {
          this.content = ''
          console.log(this.officialNoId, 'this.officialNoId1')
          Cookie.set('officialNoId', this.officialNoId, { expires: 999 })
          this.getList(false)
          this.getCount()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 更新list
    updateList(v) {
      console.log(v, 'this.officialNoId2')
      Cookie.set('officialNoId', v, { expires: 999 })
      this.getCount()
      this.getList(false)
    },

    // 查看大图
    handleShowImg(index, productImgList) {
      this.imgCurrent = index
      this.imgVisible = true
      this.imgs = productImgList
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
  }
}
</script>
<style lang="less" scoped>
.data-block {
  margin-top: 20px;
  .title-wrapper {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #e8e8e8;
    .title {
      font-weight: bold;
    }
  }
  .num {
    font-weight: bold;
    font-size: 18px;
    margin-bottom: 0;
  }
}
.user-infor /deep/.ant-descriptions-row:nth-child(1) > td span {
  font-weight: bold;
}
.img-wrapper {
  display: flex;
  justify-content: space-between;

  .img-list {
    display: flex;
  }

  .img-text {
    line-height: 60px;
    color: #999;
  }
}

.img {
  display: block;
  margin: 0 2px;
  width: 60px;
  height: 60px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
  cursor: pointer;
}
.product {
  display: flex;
  align-items: center;
  overflow: hidden;
  .img {
    display: block;
    margin: 0 2px;
    width: 60px;
    height: 60px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
    cursor: pointer;
  }
  .product-name {
    flex: 1;
    margin-left: 5px;
    width: 80px;
    text-align: left;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    word-break: break-all; /* 追加这一行代码 */
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
  }
}
.media-list {
  display: flex;
  flex-wrap: wrap;
  .media-item {
    position: relative;
      margin: 0 10px 10px 0;
      cursor: pointer;
      .icon{
        position: absolute;
        right: 5px;
        top: 5px;
        color: red;
      }
    &.img {
      width: 72px;
      height: 72px;
    }
    &.video{
        position: relative;
        width: 120px;
        height: 120px;
        cursor: pointer;
          .icon{
          position: absolute;
          right: 5px;
          top: 5px;
          color: red;
          z-index: 3;
        }
      }
  }
}
/deep/.ant-descriptions-item > span{
  vertical-align: top;
}
</style>
